package org.demo.five;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.naming.Context;
import javax.naming.InitialContext;

import sun.jdbc.odbc.ee.DataSource;

import com.ibm.db2.jcc.DB2SimpleDataSource;

/**
 * 
 * @author  
 * @date    2010-10-24
 * @file    org.demo.five.JDCTest.java
 */
public class JDCTest {

	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		JDCTest t  = new JDCTest();
		Connection conn = t.getConnectionByDataSource();
		PreparedStatement prst = conn.prepareStatement("select current date from sysibm.sysdummy1");
		ResultSet rs = prst.executeQuery();
		if (rs.next()){
			System.out.println(rs.getString(1));
		}
		rs.close();
		conn.close();
		
	}
	/**
	 * 获取数据库连接
	 * @return
	 */
	public Connection getConnection()throws Exception{
		String driver = "com.ibm.db2.jcc.DB2Driver";
		String url = "jdbc:db2://10.162.11.134:50000/sample";
		String user = "administrator";
		String pass = "admin";
		// 
		Class.forName(driver);
		return DriverManager.getConnection(url, user, pass);
	}
	/**
	 * 通过 dataSource 获取 connection
	 * @return
	 * @throws Exception
	 */
	public Connection getConnectionByDataSource()throws Exception{
		DB2SimpleDataSource dsds = new DB2SimpleDataSource();
		dsds.setServerName("10.162.11.134");
		dsds.setPortNumber(50000);
		dsds.setDatabaseName("sample");
		dsds.setUser("administrator");
		dsds.setPassword("admin");
		Context context = new InitialContext();
		context.bind("sampledb",dsds);
		// 
		DataSource ds = (DataSource)context.lookup("sampledb");
		return ds.getConnection();
	}
}
